﻿namespace EyeOpen.Data.Test
{
	using System;
	using System.Data.Entity;
	using Microsoft.VisualStudio.TestTools.UnitTesting;

	[TestClass]
	public abstract class DbContextTest<TDbContext, TDbPopulator>
		where TDbContext : DbContext
		where TDbPopulator : DbPopulator<TDbContext>, new()
	{
		protected DbContextTest()
		{
			CreateDataBase();
		}

		[TestMethod]
		public void PopulateDataBase()
		{
			using (var uow = CreateUow())
			{
				new TDbPopulator()
					.Populate(uow);
			}
		}

		/// <exception cref="ArgumentException"><c>ArgumentException</c>.</exception>
		protected TDbContext CreateUow()
		{
			var dbContextType = typeof(TDbContext);

			const string DbContextSuffix = "DbContext";

			if (!dbContextType.Name.EndsWith(DbContextSuffix))
			{
				throw new ArgumentException(string.Format("The DbContext class name must ends with \"{0}\".", DbContextSuffix));
			}

			var connectionName = dbContextType.Name.Replace(DbContextSuffix, string.Empty);

			connectionName = string.Format("{0}Connection", connectionName);

			return (TDbContext)Activator.CreateInstance(dbContextType, connectionName);
		}

		private void CreateDataBase()
		{
			var dropCreateDatabaseAlways = new DropCreateDatabaseAlways<TDbContext>();

			using (var dbContext = CreateUow())
			{
				dropCreateDatabaseAlways
					.InitializeDatabase(dbContext);

				dbContext
					.SaveChanges();
			}
		}
	}
}